﻿using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;

namespace FlickrSL
{
    public enum ResponseStatus
    {
        Ok,
        Fail
    }

    public class FlickrResponse<TElement> : IXmlSerializable
    {
        private static Boolean IXmlSerializable;
        private static XmlSerializer ElementSerializer;

        public ResponseStatus Status { get; set; }

        public TElement Element { get; set; }

        static FlickrResponse()
        {
            if (typeof(IXmlSerializable).IsAssignableFrom(typeof(TElement)))
            {
                FlickrResponse<TElement>.IXmlSerializable = true;
            }
            else
            {
                FlickrResponse<TElement>.ElementSerializer = new XmlSerializer(typeof(TElement));
            }
        }

        public XmlSchema GetSchema()
        {
            return null;
        }

        public void ReadXml(XmlReader reader)
        {
            reader.MoveToContent();

            if (reader.IsStartElement("rsp"))
            {
                this.Status = (ResponseStatus)Enum.Parse(typeof(ResponseStatus), reader.GetAttribute("stat"), true);
            }

            reader.ReadStartElement("rsp");
            reader.MoveToContent();

            if (FlickrResponse<TElement>.IXmlSerializable)
            {
                this.Element = Activator.CreateInstance<TElement>();
                ((IXmlSerializable)this.Element).ReadXml(reader);
            }
            else
            {
                this.Element = (TElement)FlickrResponse<TElement>.ElementSerializer.Deserialize(reader);
            }

            reader.ReadEndElement();
        }

        public void WriteXml(XmlWriter writer)
        {
            writer.WriteStartElement("rsp");
            writer.WriteAttributeString("stat", this.Status.ToString().ToLower());

            if (FlickrResponse<TElement>.IXmlSerializable)
            {
                ((IXmlSerializable)this.Element).WriteXml(writer);
            }
            else
            {
                FlickrResponse<TElement>.ElementSerializer.Serialize(writer, this.Element);
            }

            writer.WriteEndElement();
        }
    }
}
